﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Win32;
using Nest;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using treeView.InterfaceWindow;
using treeView.SqlDb;
using treeView.SqlDb.dbModel;

namespace treeView
{
    public partial class PLCInterface : Window
    {
        private List<ToPLCInteraceNode> allData;
        public ObservableCollection<TreeNode> RootNodes { get; set; } = new ObservableCollection<TreeNode>();

        public PLCInterface()
        {
            InitializeComponent();
            DataContext = this;
            Machine.Instance.ConncetConfigDb();
            allData = Machine.Instance.GetTreeData();

            // 填充 ComboBox
            var fileNames = allData.Select(x => x.FileName).Distinct().ToList();
            cb_FileName.ItemsSource = fileNames;

            if (fileNames.Count > 0)
            {
                cb_FileName.SelectedIndex = 0;
            }

            PopulateTreeView();
        }

        private void PopulateTreeView()
        {
 
            string selectedFileName = cb_FileName.SelectedItem as string;
            var filteredData = allData;

            if (!string.IsNullOrEmpty(selectedFileName))
            {
                filteredData = allData.Where(x => x.FileName == selectedFileName).ToList();
            }

            var topLevelNodes = Machine.Instance.BuildTree(filteredData);
            RootNodes.Clear();

            foreach (var node in topLevelNodes)
            {
                RootNodes.Add(ConvertToTreeNode(node));
            }
        }
        private void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            if (sender is TreeViewItem { DataContext: TreeNode treeNode })
            {
                SortTreeNodeChildren(treeNode);
            }
        }
        private void SortTreeNodeChildren(TreeNode node)
        {
            if (node?.Children == null) return;

            // 修改排序规则：通过ImagePath判断节点类型
            var orderedChildren = node.Children
                .OrderBy(n => n.ImagePath.Contains("根节点.png") ? 1 : 0)  // 组节点在后（值为1）
                .ThenBy(n => n.NodeName)                                   // 按名称排序
                .ToList();

            // 清空后重新添加已排序的节点
            node.Children.Clear();
            foreach (var child in orderedChildren)
            {
                node.Children.Add(child);
            }

            // 递归排序所有子节点（包含组节点）
            foreach (var child in node.Children)
            {
                SortTreeNodeChildren(child);
            }
        }
        private TreeNode ConvertToTreeNode(TreeViewItem node)
        {
            var treeNode = new TreeNode
            {
                NodeName = node.Header.ToString(),
                ImagePath = node.HasItems ?
                    "pack://application:,,,/treeView;component/Images/根节点.png" :
                    "pack://application:,,,/treeView;component/Images/子节点.png"
            };

            // 先添加原始子节点
            var rawChildren = new List<TreeViewItem>();
            foreach (var child in node.Items)
            {
                if (child is TreeViewItem childItem)
                {
                    rawChildren.Add(childItem);
                }
            }

            // 转换时即进行排序
            foreach (var childItem in rawChildren
                .OrderBy(c => c.HasItems)  // 先排无子节点的
                .ThenBy(c => c.Header.ToString()))
            {
                treeNode.Children.Add(ConvertToTreeNode(childItem));
            }

            return treeNode;
        }

        private void NodeTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (NodeTreeView.SelectedItem is TreeNode selectedNode)
            {
                var filteredData = GetFilteredData(BuildNodePath(selectedNode));
                NodeDataGrid.ItemsSource = filteredData;
            }
        }

        private string BuildNodePath(TreeNode node)
        {
            var pathParts = new List<string>();
            var currentNode = node;

            while (currentNode != null)
            {
                pathParts.Insert(0, currentNode.NodeName);
                currentNode = FindParentTreeNode(currentNode);
            }
            return string.Join("/", pathParts);
        }

        private List<ToPLCInteraceNode> GetFilteredData(string selectedPath)
        {
            var filtered = new List<ToPLCInteraceNode>();

            var leafNode = allData.FirstOrDefault(item =>
                $"{item.GroupName}/{item.NodeName}".Trim('/') == selectedPath);

            if (leafNode != null)
            {
                filtered.Add(leafNode);
            }
            else
            {
                filtered = allData.Where(item =>
                {
                    string fullPath = $"{item.GroupName}/{item.NodeName}".Trim('/');
                    string[] fullPathParts = fullPath.Split('/');
                    string[] selectedPathParts = selectedPath.Split('/');

                    return fullPathParts.Length == selectedPathParts.Length + 1 &&
                           fullPath.StartsWith(selectedPath + "/");
                }).ToList();
            }

            return filtered;
        }

        private bool IsChildPath(ToPLCInteraceNode item, string selectedPath)
        {
            string fullPath = $"{item.GroupName}/{item.NodeName}";
            return fullPath.StartsWith(selectedPath + "/");
        }

        private void cb_FileName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PopulateTreeView();
        }
        #region 节点操作
        private InterfaceAddWindow AddWindow;
        private InterfaceAddSingle addSingleWindow;

        // 添加组
        private void AddGroupMenuItem_Click(object sender, RoutedEventArgs e)
        {

            if (NodeTreeView.SelectedItem is TreeNode selectedNode)
            {
                string parentPath = BuildNodePath(selectedNode);
                if (AddWindow == null)
                {
                    AddWindow = new InterfaceAddWindow(parentPath);
                    AddWindow.GroupAdded += OnGroupAdded;
                    AddWindow.Closed += (s, e) => AddWindow = null;
                    AddWindow.Topmost = true;
                    AddWindow.Show();
                }
                else
                {
                    AddWindow.WindowState = WindowState.Normal;
                    AddWindow.Activate();
                }
            }
        }

        private void OnGroupAdded(string newGroupPath)
        {
            try
            {
                string selectedFileName = GetSelectedFileName();
                if (string.IsNullOrEmpty(selectedFileName))
                {
                    MessageBox.Show("请选择一个文件名。");
                    return;
                }
                // 数据库操作，传递 FileName
                Machine.Instance.InsertGroupToDb(selectedFileName, newGroupPath);

                // 拆分路径
                var pathParts = newGroupPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (pathParts.Length == 0) return;

                // 查找父节点（路径最后一段是新节点）
                var parentPath = string.Join("/", pathParts.Take(pathParts.Length - 1));
                var parentNode = FindTreeNodeByPath(parentPath.Split('/'));

                // 创建新节点
                var newNode = new TreeNode
                {
                    NodeName = pathParts.Last(),
                    ImagePath = "pack://application:,,,/treeView;component/Images/根节点.png"
                };

                // 添加到父节点
                if (parentNode != null)
                {
                    parentNode.Children.Add(newNode);
                    SortTreeNodeChildren(parentNode);
                }
                else // 根节点情况
                {
                    RootNodes.Add(newNode);
                    SortTreeNodeChildren(RootNodes.First());
                }

                // 更新本地数据
                allData.Add(new ToPLCInteraceNode
                {
                    FileName = selectedFileName,
                    GroupName = newGroupPath,
                    NodeName = "示例",
                    NodePreSetValue = "XXXX",
                    Type = "XXXX",
                    NodeDescription = "XXXX",
                    NodeWrite = "XXXX",
                    NodeRead = "XXXX"
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加组时出错: {ex.Message}");
            }
        }
        // 添加单个节点
        private void AddSingleMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (NodeTreeView.SelectedItem is TreeNode selectedNode)
            {
                string parentPath = BuildNodePath(selectedNode);
                if (addSingleWindow == null)
                {
                    addSingleWindow = new InterfaceAddSingle(parentPath);
                    addSingleWindow.NodeAdded += OnSingleNodeAdded;
                    addSingleWindow.Closed += (s, e) => addSingleWindow = null;
                    addSingleWindow.Topmost = true;
                    addSingleWindow.Show();
                }
                else
                {
                    addSingleWindow.WindowState = WindowState.Normal;
                    addSingleWindow.Activate();
                }
            }
        }
        private void OnSingleNodeAdded(ToPLCInteraceNode newNode)
        {
            try
            {
                string selectedFileName = GetSelectedFileName();
                if (string.IsNullOrEmpty(selectedFileName))
                {
                    MessageBox.Show("请选择一个文件名。");
                    return;
                }
                // 数据库操作
                var allNodes = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetAllList();
                newNode.Index = allNodes.Count > 0 ? allNodes.Max(node => node.Index) + 1 : 1;
                newNode.FileName = selectedFileName;
                Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.Insert(newNode);

                // 查找父节点
                var parentNode = FindTreeNodeByPath(newNode.GroupName.Split('/'));

                // 创建新节点
                var treeNode = new TreeNode
                {
                    NodeName = newNode.NodeName,
                    ImagePath = "pack://application:,,,/treeView;component/Images/子节点.png"
                };

                // 添加到父节点
                if (parentNode != null)
                {
                    parentNode.Children.Add(treeNode);
                    SortTreeNodeChildren(parentNode);
                }

                // 更新本地数据
                allData.Add(newNode);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加节点时出错: {ex.Message}");
            }
        }
        // 删除节点
        private void RemoveMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (NodeTreeView.SelectedItem is TreeNode selectedNode)
            {
                try
                {
                    var nodePath = BuildNodePath(selectedNode);
                    var dbContext = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetDbContext();

                    // 判断是否是组节点（根据图片路径）
                    bool isGroup = selectedNode.ImagePath.Contains("根节点.png");
                    string groupPath = isGroup ? nodePath : null;

                    // 删除数据库记录
                    if (isGroup)
                    {
                        // 删除所有属于该组及其子组的记录
                        var toDelete = dbContext.Set<ToPLCInteraceNode>()
                            .Where(e => e.GroupName == groupPath || e.GroupName.StartsWith(groupPath + "/"))
                            .ToList();

                        dbContext.RemoveRange(toDelete);
                    }
                    else
                    {
                        // 原删除单个节点的逻辑
                        var trackedEntity = dbContext.Set<ToPLCInteraceNode>()
                            .Local.FirstOrDefault(e => $"{e.GroupName}/{e.NodeName}".Trim('/') == nodePath);

                        if (trackedEntity == null)
                        {
                            trackedEntity = allData.FirstOrDefault(e =>
                                $"{e.GroupName}/{e.NodeName}".Trim('/') == nodePath);
                            if (trackedEntity != null)
                            {
                                dbContext.Attach(trackedEntity);
                                dbContext.Remove(trackedEntity);
                            }
                        }
                        else
                        {
                            dbContext.Remove(trackedEntity);
                        }
                    }

                    // 提交数据库更改
                    dbContext.SaveChanges();

                    // 更新本地数据
                    if (isGroup)
                    {
                        allData.RemoveAll(e =>
                            e.GroupName == groupPath ||
                            e.GroupName.StartsWith(groupPath + "/"));
                    }
                    else
                    {
                        var itemToRemove = allData.FirstOrDefault(e =>
                            $"{e.GroupName}/{e.NodeName}".Trim('/') == nodePath);
                        if (itemToRemove != null)
                            allData.Remove(itemToRemove);
                    }

                    // 从树形结构中移除节点
                    var parentNode = FindParentTreeNode(selectedNode);
                    if (parentNode != null)
                    {
                        parentNode.Children.Remove(selectedNode);
                        SortTreeNodeChildren(parentNode); // 重新排序父节点
                    }
                    else
                    {
                        RootNodes.Remove(selectedNode);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除失败: {ex.Message}\n{ex.InnerException?.Message}");
                }
            }
        }
        #region 组导入导出
        //private void InputCSVMenuItem_Click(object sender, RoutedEventArgs e)
        //{
        //    try
        //    {
        //        OpenFileDialog openFileDialog = new OpenFileDialog
        //        {
        //            Title = "选择要导入的 CSV 文件",
        //            Filter = "CSV 文件 (*.csv)|*.csv",
        //            Multiselect = false
        //        };

        //        if (openFileDialog.ShowDialog() == true)
        //        {
        //            string filePath = openFileDialog.FileName;
        //            var csvLines = File.ReadAllLines(filePath, Encoding.UTF8).Skip(1).ToList();
        //            var records = new List<ToPLCInteraceNode>();
        //            //StringBuilder errorLog = new StringBuilder();

        //            // 解析CSV记录（保持原有Index）
        //            for (int i = 0; i < csvLines.Count; i++)
        //            {
        //                try
        //                {
        //                    string line = csvLines[i];
        //                    var fields = ParseCsvLine(line).ToArray();

        //                    if (fields.Length != 9)
        //                        throw new FormatException($"字段数量不正确（应为9列，实际{fields.Length}列）");
        //                    var record = new ToPLCInteraceNode
        //                    {
        //                        Index = int.Parse(fields[0]), // 保留CSV中的原始Index
        //                        FileName = fields[1],
        //                        GroupName = fields[2],
        //                        NodeName = fields[3],
        //                        Type = fields[4],
        //                        NodeDescription = fields[5],
        //                        NodePreSetValue = fields[6],
        //                        NodeRead = fields[7],
        //                        NodeWrite = fields[8]
        //                    };

        //                    records.Add(record);
        //                }
        //                catch (Exception ex)
        //                {
        //                    MessageBox.Show("解析CSV文件错误");
        //                }
        //            }

        //            if (records.Count > 0)
        //            {
        //                using (var dbContext = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetDbContext())
        //                using (var transaction = dbContext.Database.BeginTransaction())
        //                {
        //                    try
        //                    {
        //                        foreach (var record in records)
        //                        {
        //                            // 根据Index查找现有记录
        //                            var existing = dbContext.Set<ToPLCInteraceNode>()
        //                                .FirstOrDefault(n => n.Index == record.Index);
        //                            if (existing != null)
        //                            {
        //                                // 更新现有记录（保留原Index）
        //                                dbContext.Entry(existing).CurrentValues.SetValues(record);
        //                            }
        //                            else
        //                            {
        //                                // 插入新记录（使用CSV中的Index）
        //                                dbContext.Set<ToPLCInteraceNode>().Add(record);
        //                            }
        //                        }
        //                        dbContext.SaveChanges();
        //                        transaction.Commit();
        //                        // 重新从数据库加载最新数据
        //                        allData = Machine.Instance.GetTreeData();
        //                        // 更新UI
        //                        var fileNames = allData.Select(x => x.FileName).Distinct().ToList();
        //                        cb_FileName.ItemsSource = fileNames;
        //                        if (fileNames.Count > 0) cb_FileName.SelectedIndex = 0;
        //                        PopulateTreeView();

        //                        MessageBox.Show($"成功导入/更新 {records.Count} 条记录",
        //                                      "导入完成",
        //                                      MessageBoxButton.OK,
        //                                      MessageBoxImage.Information);
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        transaction.Rollback();
        //                        throw new Exception("数据库操作失败: " + ex.Message, ex);
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"导入失败: {ex.Message}\n{ex.InnerException?.Message}",
        //                      "错误",
        //                      MessageBoxButton.OK,
        //                      MessageBoxImage.Error);
        //    }
        //}
        private void InputCSVMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Title = "选择要导入的 CSV 文件",
                    Filter = "CSV 文件 (*.csv)|*.csv",
                    Multiselect = false
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    string filePath = openFileDialog.FileName;
                    var csvLines = File.ReadAllLines(filePath, Encoding.UTF8).Skip(1).ToList();
                    var records = new List<ToPLCInteraceNode>();

                    // 解析CSV记录（保持原有Index）
                    for (int i = 0; i < csvLines.Count; i++)
                    {
                        try
                        {
                            string line = csvLines[i];
                            var fields = ParseCsvLine(line).ToArray();

                            if (fields.Length != 9)
                                throw new FormatException($"字段数量不正确（应为9列，实际{fields.Length}列）");
                            var record = new ToPLCInteraceNode
                            {
                                Index = int.Parse(fields[0]), // 保留CSV中的原始Index
                                FileName = fields[1],
                                GroupName = fields[2],
                                NodeName = fields[3],
                                Type = fields[4],
                                NodeDescription = fields[5],
                                NodePreSetValue = fields[6],
                                NodeRead = fields[7],
                                NodeWrite = fields[8]
                            };

                            records.Add(record);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("解析CSV文件错误");
                        }
                    }

                    if (records.Count > 0)
                    {
                        var dbContext = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetDbContext();
                        var transaction = dbContext.Database.BeginTransaction();
                        try
                        {
                            foreach (var record in records)
                            {
                                // 根据Index查找现有记录
                                var existing = dbContext.Set<ToPLCInteraceNode>()
                                    .FirstOrDefault(n => n.Index == record.Index);
                                if (existing != null)
                                {
                                    // 更新现有记录（保留原Index）
                                    dbContext.Entry(existing).CurrentValues.SetValues(record);
                                }
                                else
                                {
                                    // 插入新记录（使用CSV中的Index）
                                    dbContext.Set<ToPLCInteraceNode>().Add(record);
                                }
                            }
                            dbContext.SaveChanges();
                            transaction.Commit();
                            // 重新从数据库加载最新数据
                            allData = Machine.Instance.GetTreeData();
                            // 更新UI
                            var fileNames = allData.Select(x => x.FileName).Distinct().ToList();
                            cb_FileName.ItemsSource = fileNames;
                            if (fileNames.Count > 0) cb_FileName.SelectedIndex = 0;
                            PopulateTreeView();

                            MessageBox.Show($"成功导入/更新 {records.Count} 条记录",
                                          "导入完成",
                                          MessageBoxButton.OK,
                                          MessageBoxImage.Information);
                        }
                        catch (Exception ex)
                        {
                            try
                            {
                                transaction.Rollback();
                            }
                            catch (Exception rollbackEx)
                            {
                                // 记录回滚异常信息
                                System.Diagnostics.Debug.WriteLine($"事务回滚失败: {rollbackEx.Message}");
                            }
                            MessageBox.Show($"数据库操作失败: {ex.Message}\n{ex.InnerException?.Message}",
                                          "错误",
                                          MessageBoxButton.OK,
                                          MessageBoxImage.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入失败: {ex.Message}\n{ex.InnerException?.Message}",
                              "错误",
                              MessageBoxButton.OK,
                              MessageBoxImage.Error);
            }
        }

        private ToPLCInteraceNode ParseCsvToNode(string line, string parentPath, string fileName)
        {
            var fields = ParseCsvLine(line);
            if (fields.Count != 9) return null;

            return new ToPLCInteraceNode
            {
                Index = int.Parse(fields[0]),
                FileName = fileName,
                GroupName = fields[2],
                NodeName = fields[3],
                Type = fields[4],
                NodeDescription = fields[5],
                NodePreSetValue = fields[6],
                NodeRead = fields[7],
                NodeWrite = fields[8]
            };
        }

        private void OutputCSVMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (NodeTreeView.SelectedItem is TreeNode selectedNode)
            {
                try
                {
                    string selectedPath = BuildNodePath(selectedNode);
                    var filteredData = allData.Where(item =>
                        $"{item.GroupName}/{item.NodeName}".StartsWith(selectedPath + "/") ||
                        $"{item.GroupName}/{item.NodeName}" == selectedPath).ToList();

                    SaveFileDialog saveFileDialog = new SaveFileDialog
                    {
                        Title = "导出组数据",
                        Filter = "CSV 文件 (*.csv)|*.csv",
                        FileName = $"{selectedNode.NodeName}_Export.csv"
                    };

                    if (saveFileDialog.ShowDialog() == true)
                    {
                        using (var writer = new StreamWriter(saveFileDialog.FileName, false, Encoding.UTF8))
                        {
                            writer.WriteLine("Index,FileName,GroupName,NodeName,Type,NodeDescription,NodePreSetValue,NodeRead,NodeWrite");

                            foreach (var node in filteredData)
                            {
                               

                                writer.WriteLine(
                                    $"{node.Index}," +
                                    $"{EscapeCsvField(node.FileName)}," +
                                    $"{EscapeCsvField(node.GroupName)}," +
                                    $"{EscapeCsvField(node.NodeName)}," +
                                    $"{EscapeCsvField(node.Type)}," +
                                    $"{EscapeCsvField(node.NodeDescription)}," +
                                    $"{EscapeCsvField(node.NodePreSetValue)}," +
                                    $"{EscapeCsvField(node.NodeRead)}," +
                                    $"{EscapeCsvField(node.NodeWrite)}");
                            }
                        }
                        MessageBox.Show($"成功导出 {filteredData.Count} 个节点");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出失败: {ex.Message}");
                }
            }
        }
        #endregion

        #endregion
        #region dataGrid关联数据库
        // 用于记录需要更新的节点
        private List<ToPLCInteraceNode> nodesToUpdate = new List<ToPLCInteraceNode>();

        private void NodeDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (e.EditAction == DataGridEditAction.Commit)
            {
                if (e.Row.Item is ToPLCInteraceNode editedNode)
                {
                    // 查找是否已经在待更新列表中
                    var existingInList = nodesToUpdate.FirstOrDefault(n => n.Index == editedNode.Index);
                    if (existingInList != null)
                    {
                        // 更新列表中的数据
                        existingInList.NodeName = editedNode.NodeName;
                        existingInList.NodeDescription = editedNode.NodeDescription;
                        existingInList.NodePreSetValue = editedNode.NodePreSetValue;
                    }
                    else
                    {
                        // 如果不在列表中，添加到待更新列表
                        nodesToUpdate.Add(new ToPLCInteraceNode
                        {
                            Index = editedNode.Index,
                            NodeName = editedNode.NodeName,
                            NodeDescription = editedNode.NodeDescription,
                            NodePreSetValue = editedNode.NodePreSetValue
                        });
                    }
                }
            }
        }

        private void SaveChangesButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 提交所有未保存的编辑
                NodeDataGrid.CommitEdit(DataGridEditingUnit.Row, true);
                NodeDataGrid.CommitEdit();

                using (var dbContext = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetDbContext())
                {
                    foreach (var node in allData)
                    {
                        var existingNode = dbContext.Set<ToPLCInteraceNode>().Find(node.Index);
                        if (existingNode != null)
                        {
                            // 更新所有字段（或根据IsModified判断）
                            dbContext.Entry(existingNode).CurrentValues.SetValues(node);
                        }
                    }

                    dbContext.SaveChanges();
                }

                MessageBox.Show("保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}");
            }
        }

        private void WriteNode_Click(object sender, RoutedEventArgs e)
        {

        }
        #endregion
        #region 导航条功能
        private InterfaceAddFileName addFileNameWindow;
        private void btn_AddNewFile_Click(object sender, RoutedEventArgs e)
        {

            if (addFileNameWindow == null)
            {
                addFileNameWindow = new InterfaceAddFileName();
                addFileNameWindow.FileNameAdded += OnFileNameAdded;
                addFileNameWindow.Closed += (s, e) => AddWindow = null;
                addFileNameWindow.Topmost = true;
                addFileNameWindow.Show();
            }
            else
            {
                addFileNameWindow.WindowState = WindowState.Normal;
                addFileNameWindow.Activate();
            }

        }
        private void OnFileNameAdded(object sender, FileNameAddedEventArgs e)
        {
            try
            {
                string fileName = e.FileName;
                string groupName = e.GroupName;

                // 插入新的文件和组信息到数据库
                Machine.Instance.InsertGroupToDb(fileName, groupName);

                // 更新本地数据
                allData = Machine.Instance.GetTreeData();

                // 更新 ComboBox 中的文件名列表
                var fileNames = allData.Select(x => x.FileName).Distinct().ToList();
                cb_FileName.ItemsSource = fileNames;

                // 选择新添加的文件名
                cb_FileName.SelectedItem = fileName;

                // 重新填充 TreeView
                PopulateTreeView();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加文件和组时出错: {ex.Message}");
            }
        }

        private void btn_InputCsv_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建打开文件对话框
                OpenFileDialog openFileDialog = new OpenFileDialog
                {
                    Title = "选择要导入的 CSV 文件",
                    Filter = "CSV 文件 (*.csv)|*.csv",
                    Multiselect = false
                };

                if (openFileDialog.ShowDialog() == true)
                {
                    string filePath = openFileDialog.FileName;
                    // 读取 CSV 内容
                    var csvLines = File.ReadAllLines(filePath, Encoding.UTF8).Skip(1).ToList(); // 跳过标题行
                    // 解析 CSV 数据
                    var records = new List<ToPLCInteraceNode>();
                    int errorCount = 0;
                    StringBuilder errorLog = new StringBuilder();
                    for (int i = 0; i < csvLines.Count; i++)
                    {
                        try
                        {
                            string line = csvLines[i];
                            var fields = ParseCsvLine(line).ToArray();

                            // 校验字段数量
                            if (fields.Length != 9)
                            {
                                throw new FormatException($"字段数量不正确（应为9列，实际{fields.Length}列）");
                            }

                            // 映射到数据模型
                            var record = new ToPLCInteraceNode
                            {
                                Index = int.Parse(fields[0]),
                                FileName = fields[1],
                                GroupName = fields[2],
                                NodeName = fields[3],
                                Type = fields[4],
                                NodeDescription = fields[5],
                                NodePreSetValue = fields[6],
                                NodeRead = fields[7],
                                NodeWrite = fields[8]
                            };

                            records.Add(record);
                        }
                        catch (Exception ex)
                        {
                            errorCount++;
                            errorLog.AppendLine($"第 {i + 2} 行错误: {ex.Message}");
                        }
                    }
                    // 如果有错误则提示
                    if (errorCount > 0)
                    {
                        MessageBox.Show($"发现 {errorCount} 条错误记录:\n{errorLog}",
                                      "部分数据错误",
                                      MessageBoxButton.OK,
                                      MessageBoxImage.Warning);
                    }
                    // 写入数据库
                    if (records.Count > 0)
                    {
                        using (var dbContext = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetDbContext())
                        {
                            // 开启事务
                            using (var transaction = dbContext.Database.BeginTransaction())
                            {
                                try
                                {
                                    // 清空原有数据（根据需求决定是否保留）
                                    dbContext.Set<ToPLCInteraceNode>().RemoveRange(dbContext.Set<ToPLCInteraceNode>());
                                    dbContext.SaveChanges();
                                    // 批量插入新数据
                                    dbContext.Set<ToPLCInteraceNode>().AddRange(records);
                                    dbContext.SaveChanges();
                                    transaction.Commit();
                                    // 更新本地数据
                                    allData = records;
                                    // 填充 ComboBox
                                    var fileNames = allData.Select(x => x.FileName).Distinct().ToList();
                                    cb_FileName.ItemsSource = fileNames;
                                    if (fileNames.Count > 0)
                                    {
                                        cb_FileName.SelectedIndex = 0;
                                    }
                                    PopulateTreeView();
                                    MessageBox.Show($"成功导入 {records.Count} 条记录",
                                                  "导入完成",
                                                  MessageBoxButton.OK,
                                                  MessageBoxImage.Information);
                                }
                                catch (Exception ex)
                                {
                                    transaction.Rollback();
                                    throw new Exception("数据库操作失败: " + ex.Message, ex);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入失败: {ex.Message}\n{ex.InnerException?.Message}",
                              "错误",
                              MessageBoxButton.OK,
                              MessageBoxImage.Error);
            }
        }

        // CSV 解析方法（处理带引号的字段）
        private List<string> ParseCsvLine(string line)
        {
            var fields = new List<string>();
            var buffer = new StringBuilder();
            bool inQuotes = false;

            for (int i = 0; i < line.Length; i++)
            {
                char c = line[i];

                if (c == '"')
                {
                    // 处理双引号转义（""）
                    if (i < line.Length - 1 && line[i + 1] == '"')
                    {
                        buffer.Append('"');
                        i++; // 跳过下一个引号
                    }
                    else
                    {
                        inQuotes = !inQuotes;
                    }
                }
                else if (c == ',' && !inQuotes)
                {
                    fields.Add(buffer.ToString().Trim());
                    buffer.Clear();
                }
                else
                {
                    buffer.Append(c);
                }
            }

            // 添加最后一个字段
            fields.Add(buffer.ToString().Trim());
            return fields;
        }
        private void btn_OutputCsv_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建保存文件对话框
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    Title = "导出 CSV 文件",                    // 对话框标题
                    Filter = "CSV 文件 (*.csv)|*.csv",          // 文件类型过滤
                    DefaultExt = "csv",                        // 默认扩展名
                    FileName = "PLCInterface_Export.csv",       // 默认文件名
                    OverwritePrompt = true                      // 覆盖文件时提示
                };

                // 显示对话框并等待用户选择
                if (saveFileDialog.ShowDialog() == true)
                {
                    string filePath = saveFileDialog.FileName;  // 获取用户选择的路径

                    // 获取数据库全部数据
                    using (var dbContext = Machine.Instance.ConfigDbs.ToPLCInteraceNodeRepository.GetDbContext())
                    {
                        var allNodes = dbContext.Set<ToPLCInteraceNode>().ToList();

                        // 写入 CSV 文件（UTF-8 带 BOM）
                        using (var writer = new StreamWriter(filePath, false, new UTF8Encoding(true)))
                        {
                            // 写入表头
                            writer.WriteLine("Index,FileName,GroupName,NodeName,Type,NodeDescription,NodePreSetValue,NodeRead,NodeWrite");

                            // 逐行写入数据
                            foreach (var node in allNodes)
                            {
                                // 处理字段中的特殊字符（如逗号、引号）
                                string escapedGroupName = EscapeCsvField(node.GroupName);
                                string escapedNodeName = EscapeCsvField(node.NodeName);
                                string escapedDescription = EscapeCsvField(node.NodeDescription);

                                // 拼接 CSV 行
                                writer.WriteLine(
                                    $"{node.Index}," +
                                    $"{EscapeCsvField(node.FileName)}," +
                                    $"{escapedGroupName}," +
                                    $"{escapedNodeName}," +
                                    $"{EscapeCsvField(node.Type)}," +
                                    $"{escapedDescription}," +
                                    $"{EscapeCsvField(node.NodePreSetValue)}," +
                                    $"{EscapeCsvField(node.NodeRead)}," +
                                    $"{EscapeCsvField(node.NodeWrite)}"
                                );
                            }
                        }
                    }

                    MessageBox.Show("导出成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出失败: {ex.Message}",
                              "错误",
                              MessageBoxButton.OK,
                              MessageBoxImage.Error);
            }
        }

        // 辅助方法：处理 CSV 字段中的特殊字符
        private string EscapeCsvField(string field)
        {
            if (string.IsNullOrEmpty(field)) return "";

            // 如果字段包含逗号、换行符或双引号，则用双引号包裹并转义内部的双引号
            if (field.Contains(",") || field.Contains("\"") || field.Contains("\n"))
            {
                return $"\"{field.Replace("\"", "\"\"")}\"";
            }
            return field;
        }
        #endregion
        #region 辅助方法
        private TreeNode FindTreeNodeByPath(string[] pathParts)
        {
            if (pathParts.Length == 0 || (pathParts.Length == 1 && string.IsNullOrEmpty(pathParts[0])))
                return null;

            TreeNode currentNode = RootNodes.FirstOrDefault(n => n.NodeName == pathParts[0]);
            if (currentNode == null) return null;

            for (int i = 1; i < pathParts.Length; i++)
            {
                currentNode = currentNode.Children.FirstOrDefault(n => n.NodeName == pathParts[i]);
                if (currentNode == null) break;
            }
            return currentNode;
        }

        private TreeNode FindParentTreeNode(TreeNode childNode)
        {
            foreach (var rootNode in RootNodes)
            {
                var parent = FindParentRecursive(rootNode, childNode);
                if (parent != null) return parent;
            }
            return null;
        }

        private TreeNode FindParentRecursive(TreeNode currentNode, TreeNode targetNode)
        {
            if (currentNode.Children.Contains(targetNode)) return currentNode;
            foreach (var child in currentNode.Children)
            {
                var result = FindParentRecursive(child, targetNode);
                if (result != null) return result;
            }
            return null;
        }

        private string GetSelectedFileName()
        {
            return cb_FileName.SelectedItem as string;
        }
        #endregion


    }
}
